export const check = authorities => (...args) => {
  authorities = authorities || [];
  if (args.length === 0) return true;
  if (args.length > 1) {
    // 任意一项返回true即返回true，否则返回false
    return args.some(_ => check(authorities)(_));
  } else {
    const auths = args[0];
    if (auths === undefined) {
      return true;
    } else if (typeof auths === 'string') {
      return authorities.indexOf(auths) !== -1;
    } else if (Array.isArray(auths)) {
      // 每一项都返回true才返回true，否则返回false
      return auths.every(_ => check(authorities)(_));
    }
  }
};

export const checkRouteAuth = authorities => auth => {
  if (auth) {
    let auths;
    if (typeof auth === 'string' && (auths = auth.split('|').map(_ => _.trim())).length > 1) {
      return check(authorities)(...auths);
    }
    return check(authorities)(auth);
  } else {
    return true;
  }
};

const Authorized = ({ children, authorities, authority, noMatch = null }) => {
  const childrenRender = typeof children === 'undefined' ? null : children;
  return !authority || checkRouteAuth(authorities)(authority) ? childrenRender : noMatch;
};

export default Authorized;
